const axios = require('axios');
const router = require('express').Router()

const page404 = '<h1>404 Not Found!</h1>'

/**
 * @param busId 公交id，如：027-538-0
 */
router.get('/real-time-bus', async(req, res) => {
    const { busId } = req.query;

    if (!busId) {
        return res.status(404).json(req.query)
    }

    try {
        let url = `http://bus.wuhancloud.cn:9087/website//web/420100/line/${busId}.do?Type=LineDetail`
        url = encodeURI(url)
        let jsonData = (await axios.get(url)).data
        res.status(200).json(jsonData)
    } catch (e) {
        res.status(500).json(e)
    }
})

/**
 * @param stopId 公交站id，如：027-710
 */
router.get('/stop-info', async(req, res) => {
    const { stopId } = req.query;

    if (!stopId) {
        return res.status(404).json(req.query)
    }

    try {
        let url = `http://bus.wuhancloud.cn:9087/website//web/420100/stop/group/${stopId}.do?stopId=${stopId}`
        url = encodeURI(url)
        let jsonData = (await axios.get(url)).data
        res.status(200).json(jsonData)
    } catch (e) {
        res.status(500).json(e)
    }
})

/**
 * @param stopName 要搜索的公交站名，如：广埠屯
 */
router.get('/search-stop', async(req, res) => {
    const { stopName } = req.query;

    if (!stopName) {
        return res.status(404).json(req.query)
    }

    try {
        let url = `http://bus.wuhancloud.cn:9087/website//web/420100/search.do?type=stop&keyword=${stopName}`
        url = encodeURI(url)
        let jsonData = (await axios.get(url)).data
        console.log(url)
        res.status(200).json(jsonData)
    } catch (e) {
        res.status(500).json(e)
    }
})

/**
 * @param lineName 要搜索的公交名，如：538
 */
router.get('/search-line', async(req, res) => {
    const { lineName } = req.query;

    if (!lineName) {
        return res.status(404).json(req.query)
    }

    try {
        let url = `http://bus.wuhancloud.cn:9087/website//web/420100/search.do?keyword=${lineName}&type=line`
        url = encodeURI(url)
        let jsonData = (await axios.get(url)).data
        res.status(200).json(jsonData)
    } catch (e) {
        res.status(500).json(e)
    }
})

module.exports = router